package cn.lyq.card.ui.statistics

import android.content.Context
import android.content.Intent
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import cn.lyq.card.R
import cn.lyq.card.base.BaseActivity
import cn.lyq.card.data.src.Status
import com.blankj.utilcode.util.ToastUtils
import kotlinx.android.synthetic.main.act_device_statistic.*


class DeviceStatisticActivity : BaseActivity() {

    private val mModel by lazy {
        getVM(StatisticsVM::class.java)
    }
    private val mAdapter by lazy {
        DeviceStatisticAdapter(resources)
    }
    private val mType by lazy {
        intent.getIntExtra(KEY_TYPE, 0)
    }

    companion object {
        private const val KEY_TYPE = "TYPE"

        @JvmStatic
        fun start(context: Context, type: Int) {
            val starter = Intent(context, DeviceStatisticActivity::class.java)
                .putExtra(KEY_TYPE, type)
            context.startActivity(starter)
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.act_device_statistic
    }

    override fun initView() {
        super.initView()
        setMyTitle(if (mType == 0) R.string.str_my_device_statistic else R.string.str_team_device_statistic)
        rv.layoutManager = LinearLayoutManager(this)
        rv.adapter = mAdapter
        mAdapter.setEmptyView(R.layout.layout_empty)
        mAdapter.addChildClickViewIds(R.id.tvCheckDetail)
        mAdapter.setOnItemChildClickListener { _, _, position ->
            DevProxyDetailActivity.start(this, mAdapter.data[position].goodsId, 0, mType)
        }
    }

    override fun initListener() {
        super.initListener()
        refreshLayout.setOnRefreshListener {
            getData()
        }
    }

    override fun initObserver() {
        super.initObserver()
        refreshLayout.isRefreshing = true
        getData()
    }

    private fun getData() {
        mModel.posStatistic(mType).observe(this, Observer {
            when (it?.status) {
                Status.LOADING -> {
                }
                Status.SUCCESS -> {
                    mAdapter.setList(it.requireData())
                    refreshLayout.isRefreshing = false
                }
                Status.ERROR -> {
                    ToastUtils.showShort(it.message.getMsg())
                    refreshLayout.isRefreshing = false
                }
            }
        })
    }

}